/**
* Copyright (c) 2024 Huawei Technologies Co., Ltd.
* This file is a part of the CANN Open Software.
* Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
/*!
* \file global_cache.h
* \brief
*/
#ifndef IMPL_MATMUL_MODULES_GLOBAL_CACHE_H_
#define IMPL_MATMUL_MODULES_GLOBAL_CACHE_H_

namespace matmul {
class GlobalCache;
}
__BLOCK_LOCAL__ __inline__ matmul::GlobalCache* gL1Cache;
__aicore__ inline matmul::GlobalCache* GetGlobalCachePtr()
{
    return gL1Cache;
}

namespace matmul {

class GlobalCache {
public:
    __aicore__ inline GlobalCache() = default;

    __aicore__ inline void Init()
    {
        cacheSize_ = 0;
        gL1Cache = this;
        alloc_ = false;
    }

    template <class A_TYPE, class B_TYPE>
    __aicore__ inline void InitBuffer(const TCubeTiling* __restrict cubeTiling, TPipe* tpipe)
    {
        using SrcT = typename A_TYPE::T;
        constexpr int32_t c0Size_ = GetC0Size<SrcT>();
        int32_t sizeMatrix;
        uint16_t alignedDepthB1 = cubeTiling->depthB1;
        if constexpr(B_TYPE::ibShare) {
            int baseKN;
            // float input case, k_l1_b will be aligned to 16, b matrix L1 size will be larger than expected
            if constexpr (IsSameType<SrcT, float>::value) {
                uint16_t alignedBaseK = ConstCeil(cubeTiling->baseK, BLOCK_CUBE) * BLOCK_CUBE;
                baseKN = alignedBaseK * cubeTiling->baseN;
                ASCENDC_ASSERT((baseKN > 0),
                    { KERNEL_LOG(KERNEL_ERROR, "baseKN_ is %d, which should be larger than 0", baseKN); });
            // check L1 size after using aligned kb
            if ((baseKN * cubeTiling->depthA1 + baseKN * alignedDepthB1) * sizeof(float) > TOTAL_L1_SIZE) {
                // exceeding L1 size, decrease depth b1
                alignedDepthB1 = cubeTiling->baseK * cubeTiling->baseN * alignedDepthB1 / baseKN;
            }
            ASCENDC_ASSERT((alignedDepthB1 > 0), {
                KERNEL_LOG(KERNEL_ERROR, "alignedDepthB1 is %d, which should be larger than 0", alignedDepthB1);
            });
            } else if constexpr (IsSameType<SrcT, int8_t>::value) {
                baseKN = ConstCeil(cubeTiling->baseK, c0Size_) * c0Size_ *
                    ConstCeil(cubeTiling->baseN, c0Size_) * c0Size_;
            } else {
                baseKN = cubeTiling->baseK * cubeTiling->baseN;
            }
            sizeMatrix = alignedDepthB1 * baseKN * sizeof(SrcT);
        } else if constexpr (A_TYPE::ibShare) {
            int baseMK = cubeTiling->baseM * cubeTiling->baseK;
            sizeMatrix = cubeTiling->depthA1 * baseMK * sizeof(SrcT);
        } else {
            return;
        }
        tpipe->InitBuffer(cacheQue_, 1, sizeMatrix);
    }

    __aicore__ inline void InitBuffer(int32_t baseBlockSize)
    {
        if (!isInited_) {
            GetTPipePtr()->InitBuffer(cacheQue_, 1, baseBlockSize);
            isInited_ = true;
        }
    }

    template <class SrcT>
    __aicore__ inline bool Hit(__gm__ SrcT* gmAddr)
    {
        return (alloc_ && (reinterpret_cast<GM_ADDR>(gmAddr) == srcAddr_));
    }

    template <class T>
    __aicore__ inline void EnQue(const LocalTensor<T>& tensor)
    {
        ++cacheSize_;
        cacheQue_.template EnQue<T>(tensor);
    }

    template <class T>
    __aicore__ inline LocalTensor<T> DeQue()
    {
        return cacheQue_.template DeQue<T>();
    }

    template <class T>
    __aicore__ inline LocalTensor<T> AllocTensor()
    {
        if (alloc_) {
            LocalTensor<T> cache;
            cache.address_ = cacheHead_;
            return cache;
        }

        auto cache = cacheQue_.template AllocTensor<T>();
        cacheHead_ = cache.address_;
        alloc_ = true;
        return cache;
    }

    template <class T>
    __aicore__ inline void FreeTensor(LocalTensor<T>& tensor)
    {
        cacheQue_.FreeTensor(tensor);
    }

    template <class SrcT>
    __aicore__ inline void ClearCache()
    {
        cacheSize_ = 0;
        if (alloc_) {
            LocalTensor<SrcT> a;
            a.SetAddr(cacheHead_);
            cacheQue_.FreeTensor(a);
            FreeAllEvent();
            alloc_ = false;
        }
    }

    template <class SrcT>
    __aicore__ inline LocalTensor<SrcT> GetCacheHead()
    {
        LocalTensor<SrcT> a;
        a.SetAddr(cacheHead_);
        return a;
    }

    template <class SrcT>
    __aicore__ inline  void SetCacheHead(LocalTensor<SrcT>& cacheHead)
    {
        cacheHead_ = cacheHead.address_;
    }

    template <class SrcT>
    __aicore__ inline void SetOrgAddr(__gm__ SrcT* gmAddr)
    {
        srcAddr_ = reinterpret_cast<GM_ADDR>(gmAddr);
    }

    __aicore__ inline GM_ADDR GetOrgAddr()
    {
        return srcAddr_;
    }

    __aicore__ inline void FreeAllEvent()
    {
        cacheSize_ = 0;
        alloc_ = false;
        cacheQue_.FreeAllEvent();
    }

    __aicore__ inline int32_t GetCacheSize()
    {
        return cacheSize_;
    }

    __aicore__ inline void ReduceCacheSize()
    {
        --cacheSize_;
    }

    TQue<TPosition::A1, 1, 1> cacheQue_;
    TBuffAddr cacheHead_;
    GM_ADDR srcAddr_;
    int32_t cacheSize_;
    bool alloc_;
    bool isInited_ { false };
};

}
#endif // _GLOBAL_CACHE_H_